namespace Nice157Advices.Advices
{
    /// <summary>
    /// 45.为泛型类型参数指定逆变
    /// </summary>
    public static class _45
    {
        /**
         * 逆变是指方法的参数可以是 委托 或 泛型接口的参数类型的基类
         * 使用 in 关键字指定
         */

        public static void Go ()
        {
            Programmer p = new Programmer { Name = "Mike" };
            Manager m = new Manager { Name = "Capdiem" };
            Test (p, m);
        }

        static void Test<T> (IMyComparable<T> t1, T t2)
        {
            //...
            System.Console.WriteLine (t1.Compare (t2));
        }

        // 如果不为接口 IMyComparable 的泛型参数 T 指定 in 关键字，会导致 Test(p, m)编译错误
        private interface IMyComparable<in T>
        {
            int Compare (T other);
        }

        private class Employee : IMyComparable<Employee>
        {
            public string Name { get; set; }
            public int Compare (Employee other)
            {
                return Name.CompareTo (other.Name);
            }
        }

        private class Programmer : Employee, IMyComparable<Programmer>
        {
            public int Compare (Programmer other)
            {
                return Name.CompareTo (other.Name);
            }
        }

        private class Manager : Employee { }
    }
}